import time
import json
import base64
import sys
sys.stdout.reconfigure(encoding='utf-8')


class QtBridge:
    def __init__(self, pipe_name=r'\\.\pipe\TlvTool_APIBridgeCom', retry_interval=1.0):
        self.pipe_name = pipe_name
        self.retry_interval = retry_interval
        self.pipe = None
        self.connect()

    def connect(self):
        """连接到管道（阻塞等待直到成功）"""
        while True:
            try:
                self.pipe = open(self.pipe_name, 'r+b', buffering=0)
                # print(f"✅ 已连接到管道: {self.pipe_name}")
                return
            except FileNotFoundError:
                # print("⏳ 等待服务端创建管道...")
                pass
            except OSError as e:
                # print(f"⚠️ 管道不可用: {e}")
                pass
            time.sleep(self.retry_interval)

    def send(self, message: str):
        """发送字符串到服务端"""
        if not self.pipe:
            self.connect()

        try:
            data = message.encode('utf-8')
            self.pipe.write(data)
            self.pipe.flush()
        except OSError:
            # print("⚠️ 写入失败，尝试重连...")
            self.reconnect()
            self.send(message)

    def receive(self, bufsize: int = 4096) -> str:
        """阻塞等待服务端返回"""
        if not self.pipe:
            self.connect()

        try:
            data = self.pipe.read(bufsize)
            if not data:
                # 服务端关闭了管道
                # print("⚠️ 管道被关闭，重连中...")
                self.reconnect()
                return self.receive(bufsize)
            return data.decode('utf-8', errors='ignore')
        except OSError:
            # print("⚠️ 读取失败，尝试重连...")
            self.reconnect()
            return self.receive(bufsize)

    def send_and_receive(self, message: str, bufsize: int = 4096) -> str:
        """发送消息并阻塞等待响应"""
        self.send(message)
        return self.receive(bufsize)

    def reconnect(self):
        """重新连接管道"""
        try:
            if self.pipe:
                self.pipe.close()
        except Exception:
            pass
        self.pipe = None
        self.connect()

    def close(self):
        """关闭管道"""
        if self.pipe:
            try:
                self.pipe.close()
                # print("🔚 管道已关闭。")
            except Exception:
                pass
        self.pipe = None

    def SendIIC(self, addr: int, data: list, readlen: int = 0):
        hexStr = ''
        for i in range(len(data)):
            hexStr += '{:02X}'.format(data[i])

        js = {
            "cmd": 0x2,
            "addr": '{:02X}'.format(addr),
            "data": hexStr,
            "readlen": str(readlen)
        }
        self.send(json.dumps(js))
        resp = json.loads(self.receive())
        return {
            "status": resp["status"],
            "data": base64.b64decode(resp["data"])  # 收到的是base64编码的二进制数据，需要解码
        }


class Board:
    """ This is only a demo class for a Board object """

    def __init__(self):
        self._ipc = QtBridge()

    def WriteI2C(self, addr: int, reg: int, value: int):
        self._ipc.SendIIC(addr >> 1, [reg, value])

    def ReadI2C(self, addr: int, reg: int, regIndex: int=1):
        _res = self._ipc.SendIIC(addr >> 1, [reg], 1)["data"]
        if _res is None or len(_res) == 0:
            return -1
        return int(_res[0])


board = Board()
